package com.yql.common.utils;

import cn.hutool.json.JSONUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.yql.common.json.JSONObject;

import java.util.Date;

/**
 * jwt 工具类
 * 
 * @author ruoyi
 */
public class JwtUtils
{
    private static final long EXPIRE_TIME = 30 * 60 * 1000;


    private static final String USER = "user";


    public static String createToken(String jsonObject, String secret)
    {
        Algorithm algorithm = Algorithm.HMAC256(secret);
        return JWT.create().withClaim(USER, jsonObject).sign(algorithm);
    }

    public static String createToken(String jsonObject ,String secret, long expireTime)
    {
        Date date = new Date(System.currentTimeMillis() + expireTime);
        // 加密处理密码
        Algorithm algorithm = Algorithm.HMAC256(secret);
        return JWT.create().withClaim(USER, jsonObject).
                withExpiresAt(date).sign(algorithm);
    }

    public static void verify(String secret, String token)
    {
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTVerifier jwtVerifier = JWT.require(algorithm).build();
        try
        {
            jwtVerifier.verify(token);
        }
        catch (TokenExpiredException e)
        {
            throw new TokenExpiredException("token已过期");
        }
        catch (JWTVerificationException e)
        {
            throw new JWTVerificationException("token验证失败");
        }
    }

    public static <T> T getUser(String token, Class<T> clazz)
    {
        try
        {
            DecodedJWT jwt = JWT.decode(token);
            String userStr = jwt.getClaim(USER).asString();
            return JSONUtil.toBean(JSONUtil.parseObj(userStr), clazz);
        }
        catch (JWTDecodeException e)
        {
            return null;
        }
    }
}
